<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		imgUrl
	} from '../../../utils/global';
	import {
		useOrderStore,
	} from '@/store/order';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		nextTick
	} from 'vue';
	import {
		updataCheckUp,
		getOrderById,
		updataPrice
	} from '@/api/order';
	import {
		getCaseAddonListApi,
		backToPackage,
		getCaseListApi
	} from '@/api/case';

	const orderStore = useOrderStore();
	const addonData = ref([]);
	const typeList = ref([
		'男士特色项', '女士特色项', '影像检查类', '化验检查类', '心血管检查', '消化系统', '内分泌检查', '肿瘤筛查',
	]);
	const currentType = ref(0);
	const addonList = computed(() => {
		if (!addonData.value || !typeList.value || typeof addonData.value[typeList.value[currentType.value].id] ===
			'undefined') return [];
		return addonData.value[typeList.value[currentType.value].id].options
	});

	const selectedAddons = computed(() => {
		if (!addonData.value || !addonList.value) return [];
		return addonList.value.filter(item => item.isSelected);
	});

	const totalPrice = computed(() => {
		let total = 0;
		selectedAddons.value.forEach(item => {
			total += item.price
		});
		return total.toFixed(2);
	});
	const plan_list = ref([])
	onLoad(async () => {
		await nextTick();
		try {
			const results = await getCaseAddonListApi({
				planid: orderStore.customerInfo.planId
			});
			addonData.value = results;
			typeList.value = Object.keys(results).map(item => {
				return {
					id: item,
					name: results[item].title,
					gender: item == "male" ? 0 : 1,
					ismarried: item == "female_married" ? 1 : 0
				}
			});
			getDefaultCurrent()
		} catch (error) {
			console.error('getCaseAddonApi error', error);
			uni.showToast({
				title: '获取加项包详情失败',
				icon: 'none'
			});
		}
	})
	const getDefaultCurrent = () => {
		let gender = orderStore.customerInfo.gender
		// gender 0 男 1 女
		let ismarried = orderStore.customerInfo.ismarried
		let index = 0
		if (gender == 0) {
			index = typeList.value.findIndex(item => item.gender == gender)
		}
		if (gender == 1) {
			index = typeList.value.findIndex(item => item.gender == gender && item.ismarried == ismarried)
		}
		currentType.value = index
	}
	// 切换加项选择状态
	const toggleAddon = (addon) => {
		console.log(addon)
		addon.isSelected = !addon.isSelected;
		if (addon.isSelected) {
			addonList.value.map(item => {
				if (item.additionsid != addon.additionsid) {
					item.isSelected = false
				}
			})
		}


		// addonList.value.forEach(item=>{
		// 	if(addon.isSelected){
		// 		if(item.additionsid)
		// 	}
		// })

	};
	// 切换左侧按钮
	const changeType = (item, index) => {
		// male是男，female女，female_married女已婚
		let gender = orderStore.customerInfo.gender
		// gender 0 男 1 女
		let ismarried = orderStore.customerInfo.ismarried
		if (gender != item.gender) {
			uni.showToast({
				icon: "none",
				title: "性别与所选套餐不符"
			})
			return
		}
		if (gender == 1 && ismarried != item.ismarried) {
			uni.showToast({
				icon: "none",
				title: "婚姻状态与所选套餐不符"
			})
			return
		}
		currentType.value = index
		// orderStore.selectedPackage.packageid=""
	}
	const showAddonDetail = (id) => {
		// console.log(id,"id")
		// return
		uni.navigateTo({
			url: `/pages/case/addon_detail/index?id=${id}`
		});
	}

	// 继续下一步
	const continueNext = () => {
		uni.showToast({
			title: '确认加项包中...',
			icon: 'loading'
		});

		try {
			orderStore.selectedAddons.length = 0;
			selectedAddons.value.forEach(addon => {
				// 这里需要去除Proxy状态
				orderStore.addAddon(JSON.parse(JSON.stringify({
					additionsid: addon.additionsid,
					items: [...addon.items],
					name: addon.name,
					price: Number(addon.price)
				})));
			});
			// console.log(orderStore.selectedPackage.packageid_copy,"packageid_copy")
			if (selectedAddons.value.length > 0) {
				updataCheckUp({
					id: orderStore.customerInfo.id,
					additionsid: selectedAddons.value[0].additionsid
				}).then(res => {
					backToPackage({
						packageid:orderStore.selectedPackage.packageid_copy,// orderStore.selectedPackage.packageid,
						additionsid: selectedAddons.value[0].additionsid
					}).then((data) => {
						// orderStore.selectedPackage.packageid = data.packageid
						orderStore.selectedPackage.price = data.price
						orderStore.paymentInfo.finalAmount = data.price
						orderStore.selectedPackage.packageid = data.packageid
						orderStore.selectedPackage.title = data.packagename
						updataPrice({
							id: orderStore.customerInfo.id,
							price: data.price
						}).then(res => {
							uni.navigateTo({
								url: '/pages/case/orgnization/index'
							});
						})
					})
				})
			} else {
				orderStore.selectedPackage.packageid=orderStore.selectedPackage.packageid_copy
				orderStore.selectedPackage.price = 0
				orderStore.paymentInfo.finalAmount = 0
				updataCheckUp({
					id: orderStore.customerInfo.id,
					additionsid: ""
				}).then(res => {
					updataPrice({
						id: orderStore.customerInfo.id,
						price: 0
					}).then(res => {
						uni.navigateTo({
							url: '/pages/case/orgnization/index'
						});
					})
				})
				
				// 跳转到机构选择页面
				// setTimeout(() => {
				// 	uni.navigateTo({
				// 		url: '/pages/case/orgnization/index'
				// 	});
				// }, 1000);
			}



		} catch (error) {
			uni.hideToast();
			uni.showToast({
				title: '保存失败',
				icon: 'error'
			});
			console.error('保存加项失败:', error);
		}
	};
</script>

<template>
	<view class="app-addon">
		<view class="app-tip">
			<uni-icons type="chatbubble-filled" size="25" color="white"></uni-icons>
			<text>您可以根据个人需求，自愿选择加项、升级</text>
		</view>

		<view class="case-info">
			<view class="info-wrapper">
				<text>当前套餐</text>
				<text>{{ typeList[currentType].name || '入职无忧体检套餐（男）' }}</text>
			</view>
			<image :src="imgUrl('/static/img/icons/male_icon.png')" mode="aspectFill" />
		</view>

		<view class="list-wrapper">
			<view class="type-list">
				<view class="type-item" v-for="(item, index) in typeList" :key="index"
					:class="currentType === index ? 'type-item-active' : ''" @click="changeType(item,index)">
					<!--   -->
					<text>{{ item.name }}</text>
				</view>
			</view>

			<view class="type-content">
				<view v-for="(addon, index) in addonList" :key="index" class="addon-item">
					<image class="item-img" :src="imgUrl('/static/img/imgs/order-img.png')" mode="aspectFill" />

					<view class="item-info">
						<view class="item-row" @click="toggleAddon(addon)">
							<text class="item-name">{{ addon.name }}</text>
							<view class="item-check">
								<uni-icons :type="addon.isSelected ? 'checkbox-filled' : 'circle'" :size="24"
									:color="addon.isSelected ? '#FF7F36' : '#cccccc'"></uni-icons>
							</view>
						</view>
						<!-- /{{ addon.items[0].check_items.join('、') }} -->
						<text class="item-desc" style="margin-bottom: 10rpx;"></text>
						<view class="item-row">
							<text class="item-price">折扣价 ￥{{ addon.price }}</text>
							<view class="item-detail" @click="showAddonDetail(addon.additionsid)">
								<text>详情</text>
								<uni-icons type="right" size="18" color="#333333"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="bottom-wrapper">
			<view class="bottom-row">
				<text>
					合计：
					<text class="price-text">￥{{ totalPrice }}</text>
				</text>

				<text>
					已加
					<text class="count-text">{{ selectedAddons.length }}</text>
					项。
				</text>
			</view>

			<view class="bottom-button" @click="continueNext">下一步</view>
		</view>
	</view>
</template>

<style src="./style.scss" scoped />